#include "logindialog.h"
#include "ui_logindialog.h"
#include "mainwindow.h" // 确保这个头文件存在
#include "session.h"
#include <QSqlError>
#include <QDebug>
#include <QCryptographicHash>
#include <QMessageBox>
#include <QSqlQuery>
#include <QPainter>


LoginDialog::LoginDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::LoginDialog)
{
    ui->setupUi(this);
    // 初始化用户登录数据库
    initDatabase();
    ui->label_3->setStyleSheet(R"(
        QLabel {
            font-size: 24px;
            font-weight: bold;
            color: #2c3e50;
            border-bottom: 2px solid #3498db;
            padding-bottom: 5px;
            letter-spacing: 2px;
        }
    )");
    // 设置密码输入框为密码模式
    ui->lineEditPassword->setEchoMode(QLineEdit::Password);

    this->setStyleSheet(R"(
           QDialog#LoginDialog {
               background-color: #f0f3f7;
           }
           QWidget#widget_3 {
               background-color: white;
               border-radius: 10px;
               border: 1px solid #cbd2d9;
               padding: 20px;
           }
           QLabel {
               font-weight: 600;
               font-size: 14px;
               color: #555;
           }
           QLineEdit {
               border: 1.5px solid #a0a9b8;
               border-radius: 6px;
               padding: 6px 8px;
               font-size: 14px;
               color: #333;
               background-color: #fff;
           }
           QLineEdit:focus {
               border-color: #3498db;
               background-color: #f5fbff;
           }
           QPushButton#pushButtonLogin, QPushButton#pushButtonSeg {
               background-color: #3498db;
               color: white;
               font-weight: 600;
               border-radius: 8px;
               padding: 8px 20px;
               font-size: 15px;
               border: none;
           }
           QPushButton#pushButtonLogin:hover, QPushButton#pushButtonSeg:hover {
               background-color: #5dade2;
           }
           QPushButton#pushButtonLogin:pressed, QPushButton#pushButtonSeg:pressed {
               background-color: #2e86c1;
           }
       )");
   }

void LoginDialog::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    QPixmap pixmap("C:/Users/m1937/Pictures/Screenshots/bcc.png");
    painter.drawPixmap(this->rect(), pixmap);
}


LoginDialog::~LoginDialog()
{
    // 在对话框关闭时关闭用户数据库连接
    if (db.isOpen()) {
        db.close();
        qDebug() << "用户数据库已关闭。";
    }
    // m_culturalDbManager 会因为父子关系自动删除，但显式删除也无妨
    // delete m_culturalDbManager; // 如果没有设置父对象，则需要手动删除
    delete ui;
}

// 初始化用户数据库连接和表
void LoginDialog::initDatabase()
{
    // 检查是否已经存在名为 "user_connection" 的连接
    if (QSqlDatabase::contains("user_connection")) {
        db = QSqlDatabase::database("user_connection");
    } else {
        // 如果不存在，则添加一个新的数据库连接，并命名为 "user_connection"
        db = QSqlDatabase::addDatabase("QSQLITE", "user_connection");
        db.setDatabaseName("user_data.db"); // 用户数据库文件名
    }


    if (!db.open()) {
        QMessageBox::critical(this, "数据库错误", "无法打开用户数据库: " + db.lastError().text());
        qDebug() << "无法打开用户数据库: " << db.lastError().text();
        return;
    }

    QSqlQuery query(db);
    // 创建用户表，如果不存在的话
    bool res = query.exec(
        "CREATE TABLE IF NOT EXISTS users ("
        "visitor_id INTEGER PRIMARY KEY AUTOINCREMENT,"
        "username TEXT UNIQUE NOT NULL,"
        "password TEXT NOT NULL"
        ");"
    );
    if (res) {
        qDebug() << "用户表创建或已存在。";
    } else {
        QMessageBox::critical(this, "数据库错误", "无法创建用户表: " + query.lastError().text());
        qDebug() << "无法创建用户表: " << query.lastError().text();
    }
}

// 对密码进行哈希处理 (使用 SHA256)
QString LoginDialog::hashPassword(const QString &password)
{
    QByteArray hash = QCryptographicHash::hash(password.toUtf8(), QCryptographicHash::Sha256);
    return QString(hash.toHex());
}

// 注册按钮槽函数
void LoginDialog::on_pushButtonSeg_clicked()
{
    QString username = ui->lineEditUsername->text().trimmed(); // 去除首尾空格
    QString password = ui->lineEditPassword->text();

    if (username.isEmpty() || password.isEmpty()) {
        QMessageBox::warning(this, "注册失败", "用户名和密码不能为空！");
        return;
    }

    if (!db.isOpen()) {
        QMessageBox::critical(this, "数据库错误", "用户数据库未连接，无法注册！");
        return;
    }

    QSqlQuery query(db);
    // 检查用户名是否已存在
    query.prepare("SELECT username FROM users WHERE username = :username;");
    query.bindValue(":username", username);
    if (query.exec() && query.next()) {
        QMessageBox::warning(this, "注册失败", "该用户名已被注册，请选择其他用户名！");
        return;
    }

    // 插入新用户
    QString hashedPassword = hashPassword(password); // 哈希密码
    query.prepare("INSERT INTO users (username, password) VALUES (:username, :password);");
    query.bindValue(":username", username);
    query.bindValue(":password", hashedPassword);

    if (query.exec()) {
        // 插入成功后，查出该用户的 visitor_id
        QSqlQuery idQuery(db);
        idQuery.prepare("SELECT visitor_id FROM users WHERE username = :username;");
        idQuery.bindValue(":username", username);
        if (idQuery.exec() && idQuery.next()) {
            int newVisitorId = idQuery.value(0).toInt();
            Session::setVisitorId(newVisitorId);
            Session::setUsername(username);
            qDebug() << "注册成功，visitor_id:" << newVisitorId;
        }
        QMessageBox::information(this, "注册成功", "用户注册成功！");
        ui->lineEditUsername->clear();
        ui->lineEditPassword->clear();
    } else {
        QMessageBox::critical(this, "注册失败", "注册失败: " + query.lastError().text());
        qDebug() << "注册失败: " << query.lastError().text();
    }
}

QString LoginDialog::currentUsername() {
    return m_currentUsername;
}
// 登录按钮槽函数
void LoginDialog::on_pushButtonLogin_clicked()
{
    QString username = ui->lineEditUsername->text().trimmed();
    QString password = ui->lineEditPassword->text();

    if (username.isEmpty() || password.isEmpty()) {
        QMessageBox::warning(this, "登录失败", "请输入用户名和密码！");
        return;
    }

    if (!db.isOpen()) {
        QMessageBox::critical(this, "数据库错误", "用户数据库未连接，无法登录！");
        return;
    }

    QSqlQuery query(db);
    query.prepare("SELECT password FROM users WHERE username = :username;");
    query.bindValue(":username", username);

    if (query.exec() && query.next()) {
        QString storedHashedPassword = query.value(0).toString();
        QString enteredHashedPassword = hashPassword(password); // 哈希输入的密码

        if (storedHashedPassword == enteredHashedPassword) {
            QMessageBox::information(this, "登录成功", "欢迎，" + username + "！");
            m_currentUsername = username;
            Session::setUsername(username);

            // 查找并设置 visitor_id
            QSqlQuery idQuery(db);
            idQuery.prepare("SELECT visitor_id FROM users WHERE username = :username;");
            idQuery.bindValue(":username", username);
            if (idQuery.exec() && idQuery.next()) {
                int visitorId = idQuery.value(0).toInt();
                Session::setVisitorId(visitorId);
            }

            // 管理员判定（简单示例，用户名和密码都为"1"时视为管理员）
            bool isAdminUser = (username == "1" && password == "1");
            Session::setIsAdmin(isAdminUser);

            // 打开文化建筑数据库（可选）
            if (DatabaseManager::instance().openDatabase("cultural_buildings_new.db")) {
                if (DatabaseManager::instance().initTables()) {
                    qDebug() << "武汉市文化建筑数据库已成功创建或初始化。";
                } else {
                    qDebug() << "初始化武汉市文化建筑数据库表失败。";
                }
            } else {
                qDebug() << "打开武汉市文化建筑数据库失败。";
            }

            accept();
            MainWindow *mainWin = new MainWindow();
            mainWin->show();
        } else {
            QMessageBox::warning(this, "登录失败", "密码不正确！");
        }
    }
}
